/*
 * @Author: xiaosihan
 * @Date: 2024-07-11 10:22:49
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-08-14 10:49:28
 */
import express from "express";
import { ValidationChain, body, validationResult } from "express-validator";
import fs from "fs";
import { get, isEmpty } from "lodash";
import mysql from "mysql2";
import path from "path";
import utils from "../utils";

// 服务基类
export default class ServiceBase {
  constructor() {}

  // 提取post get参数
  getParame(req: express.Request) {
    return {
      ...(get(req, ["user"]) || {}),
      ...(get(req, ["adminUser"]) || {}),
      ...req.query,
      ...req.body,
    };
  }

  // 判断是否登录
  isLogin(req: express.Request) {
    return !isEmpty(get(req, ["user"]));
  }

  // 判断是否管理员
  isAdmin(req: express.Request) {
    return !isEmpty(get(req, ["adminUser"]));
  }

  //创建一个判空的中间件
  paramNotEmpty(params: Array<string>) {
    return async (
      req: express.Request,
      res: express.Response,
      next: express.NextFunction
    ) => {
      const emptyParam = [];
      for (let p of params) {
        if (isEmpty(req.query[p]) && isEmpty(req.body[p])) {
          // 记录空参数
          emptyParam.push(p);
        }
      }
      if (!isEmpty(emptyParam)) {
        this.error(res, `${emptyParam.join(",")}不能为空`);
      } else {
        next();
      }
    };
  }

  // 递归读取文件
  async walkDir(directory: string, callback: Function) {
    return new Promise<void>((resolve, reject) => {
      fs.readdir(directory, async (err, files) => {
        if (err) return console.error(err);

        for (let file of files) {
          const fullPath = path.join(directory, file);

          await new Promise<void>((resolve2, reject) => {
            fs.stat(fullPath, (err, stats) => {
              if (err) return console.error(err);

              if (stats.isDirectory()) {
                this.walkDir(fullPath, callback);
                resolve2();
              } else if (stats.isFile()) {
                callback(fullPath);
                resolve2();
              }
            });
          });
        }
        resolve();
      });
    });
  }

  // 获取文件名的后缀
  getSuffix(filename: string) {
    const match = filename.match(/\.([^\.]+)$/);
    return match ? match[1].toLowerCase() : "";
  }

  // 返回成功的状态
  success(res: express.Response, data: any = undefined, message = "成功") {
    if (get(res, ["_headerSent"])) return;
    res.send({
      status: "success",
      code: 200,
      message,
      data,
    });
  }

  //返回失败的状态
  error(res: express.Response, message = "失败") {
    if (get(res, ["_headerSent"])) return;
    res.send({
      status: "error",
      code: 401,
      message,
    });
  }
}
